package cn.topevery.garden.dal.logic;

import cn.hutool.core.bean.BeanUtil;
import cn.topevery.garden.dal.dao.GreTransplantDao;
import cn.topevery.garden.dal.dao.GreTransplantFileDao;
import cn.topevery.garden.dal.util.ExcelImportUtil;
import cn.topevery.garden.entity.dto.GreTransplantDTO;
import cn.topevery.garden.framework.Database;
import cn.topevery.garden.entity.po.GreTransplant;
import cn.topevery.garden.entity.query.GreTransplantQuery;
import cn.topevery.garden.entity.vo.GreTransplantVO;
import cn.topevery.garden.framework.base.BaseLogic;
import hw.topevery.basis.runtime.UserRuntime;
import hw.topevery.framework.db.base.BaseEntityDao;
import hw.topevery.framework.db.entity.DataPager;
import hw.topevery.framework.db.entity.SqlUpdateMate;
import hw.topevery.framework.db.enums.ScriptConditionEnum;
import hw.topevery.framework.entity.KeyValue;
import hw.topevery.framework.web.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.function.Predicate;

/**
 * 占绿移植信息管理表
 *
 * @author code-generate
 * @date 2023-03-03
 */
@Service
public class GreTransplantLogic extends BaseLogic<GreTransplant> {
    @Autowired
    GreTransplantDao greTransplantDao;

    @Override
    public BaseEntityDao<GreTransplant, Integer> getDao() {
        return greTransplantDao;
    }


    /**
     * 获取列表
     *
     * @param query
     */
    public DataPager<GreTransplantVO> listPage(GreTransplantQuery query) {
        DataPager<GreTransplantVO> page = greTransplantDao.listPage(query);
        page.records.forEach(vo -> vo.setFileList(greTransplantFileDao.getListEntityByColumns(new ArrayList<KeyValue>(2) {{
            add(new KeyValue<>("c_db_status", 0));
            add(new KeyValue<>("c_transplant_id", vo.getId()));
        }})));
        return page;
    }

    /**
     * 根据自增id批量删除
     *
     * @param ids
     */
    public void deleteBatchById(String userId, Integer[] ids) {
        Database.transactionScope(() -> {
            delete(userId, ids);
            SqlUpdateMate sqlUpdateMate = new SqlUpdateMate("t_gre_transplant_file");
            sqlUpdateMate.setColumnValue(true, "c_db_status", 1)
                    .where(true, "c_transplant_id", ScriptConditionEnum.In, ids);
            boolean isOk = greTransplantFileDao.updateSqlUpdateMate(sqlUpdateMate);
            if (!isOk) {
                throw new RuntimeException("删除失败！");
            }
        });
    }

    @Autowired
    private GreTransplantFileDao greTransplantFileDao;

    /**
     * 根据自增id保存或者更新
     *
     * @param dto 实体
     */
    public void saveOrUpdate(String userId, @Valid GreTransplantDTO dto) {
        Database.transactionScope(() -> {
            GreTransplant greTransplant = BeanUtil.copyProperties(dto, GreTransplant.class);
            if (dto.getId() == null) {
                greTransplantDao.insertEntity(userId, greTransplant);
            } else {
                greTransplantFileDao.updateByTable(userId,
                        Collections.singletonList(new KeyValue<>("c_db_status", 1)),
                        new ArrayList<KeyValue>(2) {{
                            add(new KeyValue<>("c_transplant_id", dto.getId()));
                            add(new KeyValue<>("c_db_status", 0));
                        }});
                greTransplantDao.update(userId, greTransplant);
            }
            if (!CollectionUtils.isEmpty(dto.getFileList())) {
                dto.getFileList().forEach(f -> f.setTransplantId(greTransplant.getId()));
                greTransplantFileDao.insert(userId, dto.getFileList());
            }
        });
    }

    /**
     * 根据自定义列值来获取对象
     */
    public GreTransplant getEntityByColumn(String key, String value) {
        return greTransplantDao.getEntityByColumn(key, value);
    }

    public JsonResult<?> analysisExcel(MultipartFile file) {
        try {
            Map<String, Object> map = ExcelImportUtil.analysisExcel(file.getInputStream(), GreTransplantVO.class, filterFunc());
            return JsonResult.ok(map);
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.error("解析发生错误，请按照模板格式填写数据！");
        }
    }

    private Predicate<GreTransplantVO> filterFunc() {
        return vo -> {
            if (vo.getStartDate() != null && vo.getEndDate() != null && vo.getEndDate().isBefore(vo.getStartDate())) {
                vo.setErrorMessage("结束日期不能早于开始日期！");
                return true;
            }
            return false;
        };
    }

    public JsonResult<?> importExcel(List<GreTransplantVO> greLandVOList) {
        return ExcelImportUtil.importExcel(greLandVOList, filterFunc(),
                vo -> BeanUtil.copyProperties(vo, GreTransplant.class),
                entities -> greTransplantDao.insert(UserRuntime.getSysUser().id.toString(), entities));
    }
}
